#ifndef __SERVICE_SERVER_H__
#define __SERVICE_SERVER_H__


#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <map>
#include <vector>

class InfoChannel {
public:
	boost::shared_ptr<boost::asio::ip::tcp::acceptor > pAcceptor;
	boost::shared_ptr<boost::asio::ip::tcp::socket> pSocketSrc;
	boost::shared_ptr<boost::asio::ip::tcp::socket> pSocketDesc;

	boost::shared_ptr<boost::asio::ip::tcp::socket> pSocket;
};
typedef boost::shared_ptr<InfoChannel> InfoChannelPtr;

class InfoRead {
public:
	boost::shared_ptr<boost::asio::ip::tcp::socket> pSocket;
	boost::shared_ptr<std::vector<unsigned char> > pBuffer;
	std::string key;
};
typedef boost::shared_ptr<InfoRead> InfoReadPtr;

class ServiceServer : public boost::enable_shared_from_this<ServiceServer>
{
public:
	typedef boost::shared_ptr<boost::asio::io_service> service_ptr;
	typedef boost::shared_ptr<boost::asio::ip::tcp::socket> socket_ptr;
	typedef boost::shared_ptr<std::vector<unsigned char> > buffer_ptr;
	typedef buffer_ptr::element_type::iterator iter_type;
	typedef boost::shared_ptr<boost::asio::ip::tcp::acceptor > acceptor_ptr;

	virtual bool start();
	virtual void stop();
	virtual void setInfo(const int connectPort);
protected:
	virtual void handleThread(service_ptr pService, const int connectPort);
	virtual void handleAcceptor(const boost::system::error_code& ec, socket_ptr pSocket, InfoChannelPtr pChannel);
	virtual void handleRead(const boost::system::error_code& ec, size_t Count, buffer_ptr pBuffer, socket_ptr pSocket, InfoReadPtr pInfo);
	virtual unsigned char calCrc(iter_type IterStart, iter_type IterEnd);
	virtual void handleWrite(const boost::system::error_code& ec, size_t Count, buffer_ptr pBuffer);
	virtual buffer_ptr getFrame(unsigned int count, buffer_ptr pBuffer, InfoReadPtr pInfo);
	virtual bool decodeFrame(unsigned int count, buffer_ptr pBuffer, InfoReadPtr pInfo);
	virtual void handleAcceptorData(const boost::system::error_code& ec, socket_ptr pSocket, InfoChannelPtr pChannel);
	virtual bool addChannel(const int port, socket_ptr pSocket, unsigned char& errorCode);
	virtual bool updateChannel(const int port, socket_ptr pSocket, unsigned char& errorCode);
	virtual void handleReadData(const boost::system::error_code& ec, size_t Count, buffer_ptr pBuffer, socket_ptr pSocket, InfoChannelPtr pChannel);
	virtual std::string frame2string(buffer_ptr pBuffer, unsigned int count);
	virtual InfoChannelPtr removeChannel(const int port);
	virtual void closeChannel(InfoChannelPtr pChannel);

	int m_connnectPort;
	boost::thread m_thread;
	service_ptr m_pService;
	socket_ptr m_pSocket;
	acceptor_ptr m_pAcceptor;
	std::map<std::string, InfoChannelPtr> m_MapChannel;
};
typedef boost::shared_ptr<ServiceServer> ServiceServerPtr;


#endif


